<style scoped>
.item-disabled {
    margin-bottom: 0;
}
.type-box {
    display: flex;
    flex-flow: row;
}
.item-title {
    text-align: center;
}
</style>
<template>
    <div class="Business">
        <Form ref="formData" :model="formData"  :label-width="120" >
            <Row>
                <Row>

                    <Table :loading="loading" border :columns="readOnly ? costExemptDetailColumns : columns" :data="data" sortable="custom"
                               @on-sort-change="changeSort" ref="selection">

                        <template slot-scope="{row,index}" slot="exemptionAmt">
                            <Form  :ref='"form1"+index' :model='row' >
                                <FormItem prop="exemptionAmt" :rules='{required:true,message:"请输入豁免金额！"}'>
                                    <InputNumber
                                        :disabled="readOnly || isApprove || row.remainingAmt==0"
                                        @on-change="changeReductionRatio(row,index)"
                                        clearable
                                        :max=row.costAmt
                                        :min="0"
                                        v-model="row.exemptionAmt"></InputNumber>
                                </FormItem>
                            </Form>
                        </template>

                        <!-- 比例=到期金额/费用金额-->
                        <template slot-scope="{row,index}" slot="reductionRatio" >
                            <Form  :ref='"form1"+index' :model='row'>
                                <FormItem prop="reductionRatio" :rules='{required:true,message:"请输入减免比例！"}' >

                                    <InputNumber
                                        :disabled="readOnly || isApprove || row.remainingAmt==0"
                                        @on-change="changeexemptionAmt(row,index)"
                                        :max="100"
                                        :min="0"
                                        clearable
                                        v-model="row.reductionRatio"
                                        :formatter="value => `${value}%`"
                                        :parser="value => value.replace('%', '')"></InputNumber>
                                </FormItem>
                            </Form>
                        </template>

                        <template slot-scope="{ row, index }" slot="status">
                            <span>{{getTitle(row.status)}}</span>
                        </template>
                        <template slot-scope="{ row, index }" slot="costType">
                            <span>{{getTitle('feeType',row.costType)}}</span>
                        </template>

                    </Table>
                </Row>

                <Row type="flex" justify="end" class="page">
                    <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize"
                          @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]"
                          size="small" show-total show-elevator show-sizer></Page>
                </Row>

                <Row>
                    <!--<Col span="8">
                        <Form-item label="显示全部" prop="showAll" >
                            <radio-group v-model.trim="showAll">  &lt;!&ndash;@on-change="selectRadio"&ndash;&gt;
                                <radio label="00">显示全部</radio>
                            </radio-group>
                        </Form-item>
                    </Col>-->

                  <!--  <Col span="4">
                        <span>费用总计:</span><span>xxxx</span>
                    </Col>-->

                    <Col span="8">
                        <span>费用金额总计:</span><span>{{this.totalCostAmt}}</span>
                    </Col>

                    <Col span="8">
                        <span>豁免额总计:</span><span>{{this.totalExemptAmt}}</span>
                    </Col>

                    <Col span="8">
                        <span>到期金额总计:</span><span>{{this.totalDueAmt}}</span>
                    </Col>

                </Row>

            </Row>
        </Form>
    </div>
</template>
<script>
    import {
        costExemptApprove,
        getCanCostExemptListByContractNo,
        getCostExemptListByExemptId,
        saveCostExemptList,
        submitCostExemptList,
    } from "@/projects/basic/api/contract/cost-exempt/costExempt";
    import {verifyErrorToView} from "_p/basic/assets/contract/js/utils";
    import {getTitleFromDataDict} from "_p/basic/assets/contract/js/utils";

    import PlaceCascade from "_p/basic/pages/contract/common/PlaceCascade";

    export default {
    components: { PlaceCascade },
    props: {
        dataDict: {
            type: Object,
            required: true
        },
        isApprove: {
            type: Boolean,
            require: true
        },
        //对象参数包含：合同号码、角色类型
        Obj: {
            type: Object,
            required: true
        },
        pageParams: {
            type: Object,
            required: true
        },
        businessSource: {
            type: String,
            required: true
        },
        isLoan: {
            type: String,
            required: true
        },

    },
    data() {
        return {
            loading: false,
            //费用总计
            totalCost:0,
            //费用金额总计
            totalCostAmt:0,
            //豁免金额总计
            totalExemptAmt:0,
            //到期金额总计
            totalDueAmt:0,

            indeterminate: false,
            checkAllType: false,
            isSave: false,
            type: "",
            changeSubject: "",
            business: "",
            initLoadData: [],


            formData: {
                reductionRatio:"",
                costType:"",
                exemptionAmt:"",
            },

            exemptFrom :{
                reductionRatio:"",
                costType:"",
                exemptionAmt:"",
            },

            searchForm: {
                pageNumber: 1,
                pageSize: 10,
            },

            columns: [
                {
                    type: 'index',
                    title:"序号",
                    minWidth: 80,
                    align: "center",
                    fixed: "left"

                },
                {
                    title: "费用类型",
                    key: "costType",
                    slot: "costType",
                    minWidth: 150,
                },
                {
                    title: "内部合同号",
                    key: "contractNo",
                    minWidth: 180,
                    align: "center",
                    //sortable: true
                },
                {
                    title: "客户姓名",
                    key: "custName",
                    minWidth: 130,
                    align: "center",
                },
                {
                    title: "到期日",
                    key: "dueDate",
                    minWidth: 120,
                    align: "center",
                },
                {
                    title: "费用总计",
                    key: "totalCost",
                    minWidth: 150,
                    align: "center",
                },

                {
                    title: "费用金额",
                    key: "costAmt",
                    minWidth: 150,
                    align: "center",

                },
                {
                    title: "减免比例%",
                    key: "reductionRatio",
                    slot: "reductionRatio",
                    minWidth: 150,
                    align: "center",
                },
                {
                    title: "豁免金额",
                    key: "exemptionAmt",
                    slot: "exemptionAmt",
                    minWidth: 150,
                    align: "center",
                },

                {
                    title: "累计豁免金额",
                    key: "exemptedAmt",
                    minWidth: 150,
                    align: "center",

                },
                {
                    title: "核销额",
                    key: "receivedAmt",
                    minWidth: 150,
                    align: "center",

                },
                {
                    title: "到期金额",
                    key: "dueAmt",
                    minWidth: 150,
                    align: "center",

                },
                {
                    title: "处理状态",
                    key: "status",
                    slot: "status",
                    minWidth: 120,
                    align: "center",

                },
                /*{
                    title: "生效日",
                    key: "effectiveDate",
                    minWidth: 120,
                    align: "center",
                },*/

            ],
            costExemptDetailColumns: [
                {
                    type: 'index',
                    title:"序号",
                    minWidth: 80,
                    align: "center",
                    fixed: "left"

                },
                {
                    title: "费用类型",
                    key: "costType",
                    slot: "costType",
                    minWidth: 150,
                },
                {
                    title: "内部合同号",
                    key: "contractNo",
                    minWidth: 180,
                    align: "center",
                    //sortable: true
                },
                {
                    title: "客户姓名",
                    key: "custName",
                    minWidth: 130,
                    align: "center",
                },
                {
                    title: "到期日",
                    key: "dueDate",
                    minWidth: 120,
                    align: "center",
                },
                {
                    title: "费用总计",
                    key: "totalCost",
                    minWidth: 150,
                    align: "center",
                },

                {
                    title: "费用金额",
                    key: "costAmt",
                    minWidth: 150,
                    align: "center",

                },
                {
                    title: "减免比例%",
                    key: "reductionRatio",
                    slot: "reductionRatio",
                    minWidth: 150,
                    align: "center",
                },
                {
                    title: "豁免金额",
                    key: "exemptionAmt",
                    slot: "exemptionAmt",
                    minWidth: 150,
                    align: "center",
                },

                {
                    title: "到期金额",
                    key: "dueAmt",
                    minWidth: 150,
                    align: "center",

                },
                {
                    title: "处理状态",
                    key: "status",
                    slot: "status",
                    minWidth: 120,
                    align: "center",

                },
                /*{
                    title: "生效日",
                    key: "effectiveDate",
                    minWidth: 120,
                    align: "center",
                },*/

            ],
            data: [],
            total: 0,
            readOnly:false,
        };
    },
    mounted() {
        this.init();
    },
    methods: {
        init() {
            //获取当前合同下所有豁免金额列表
            this.getList(this.Obj);
            this.readOnly = this.Obj.readOnly;
        },

        //翻页
        changeSort(e) {
            this.searchForm.sort = e.key;
            this.searchForm.order = e.order;
            if (e.order === "normal") {
                this.searchForm.order = "";
            }

        },
        changePage(v) {
            this.searchForm.pageNumber = v;
            this.getCostExemptList();
            this.clearSelectAll();
        },
        changePageSize(v) {
            this.searchForm.pageSize = v;
            this.getCostExemptList();
        },


        getList(v){
            let param ={
                contractNo:v.contractNo,
                exemptId:v.id,
                pageSize:this.searchForm.pageSize,
                pageNumber:this.searchForm.pageNumber
            }
            if(this.Obj.readOnly){
                this.readOnly=true;
                getCostExemptListByExemptId(param).then(res => {
                    if (res.code === "0000") {
                        //初始化处理金额信息
                        this.handleCostForCheck(res.data.records);
                        this.total = res.data.total;
                    }
                });
            }else{
                getCanCostExemptListByContractNo(param).then(res => {
                    if (res.code === "0000") {
                        //初始化处理金额信息
                        this.handleCost(res.data.records);
                        this.total = res.data.total;
                    }
                });
            }
        },

        //编辑页面用
        handleCost(param){
            //费用金额 = 表剩余应收金额   费用总计 = 表中费用金额
            //豁免金额 = 剩余应收金额

            param.forEach((item)=>{
                item.expenseDetailId = item.id;
                //费用总计 = 表中费用金额
                item.totalCost = item.costAmt;
                //费用金额 = 表中剩余应收金额
                item.costAmt = item.remainingAmt;
                item.dueDate=item.endDate ;
                item.exemptionAmt = item.remainingAmt;
                item.exemptionAmt == 0 ?  item.reductionRatio= 0 : item.reductionRatio= 100
                //到期金额=费用金额-豁免金额
                item.dueAmt = 0 ;
                this.totalCostAmt +=item.remainingAmt;
                this.totalExemptAmt +=item.exemptionAmt;
                this.totalDueAmt +=item.dueAmt;
               // this.businessSource = this.businessSource;
                item.processPerson = this.isLoan;
            })
            this.data = param;
            console.log(this.isLoan)
        },

        //查看页面用
        handleCostForCheck(param){
            param.forEach((item)=>{
                this.totalCostAmt +=item.costAmt;
                this.totalExemptAmt +=item.exemptionAmt;
                this.totalDueAmt +=item.dueAmt;
            })
            this.data = param;
        },

        //更改豁免额时,比例联动
        changeReductionRatio(row,index){
            this.data[index].exemptionAmt=row.exemptionAmt
            this.data[index].dueAmt =  this.data[index].totalCost - this.data[index].exemptionAmt -this.data[index].receivedAmt - this.data[index].remainingAmt;
            let num = row.exemptionAmt / row.remainingAmt * 100;
            //this.data[index].reductionRatio =(row.exemptionAmt / row.costAmt * 100).toFixed(2);
            this.data[index].reductionRatio =Math.round(num*100)/100;

            this.changeTotal();
            console.log(this.data)
        },
        //更改比例时,豁免额联动
        changeexemptionAmt(row,index){
            this.data[index].reductionRatio =  row.reductionRatio
            let num = row.reductionRatio * row.remainingAmt / 100;
            this.data[index].exemptionAmt = Math.round(num*100)/100;
            this.data[index].dueAmt =  this.data[index].totalCost - this.data[index].exemptionAmt -this.data[index].receivedAmt  - this.data[index].remainingAmt;

            this.changeTotal();
        },

        changeTotal(){
            this.totalCostAmt=0
            this.totalExemptAmt=0
            this.totalDueAmt=0
            this.data.forEach((item)=>{
                this.totalCostAmt +=item.remainingAmt;
                this.totalExemptAmt +=item.exemptionAmt;
                this.totalDueAmt +=item.dueAmt;
            })
        },


  /*      save() {
            this.$refs.formData.validate(valid => {
                console.log(this.formData, " this.$refs.formData");

                if (valid) {
                    let data = Object.assign({}, this.formData, this.Obj);
                    changeContactChange(data)
                        .then(res => {
                            this.$emit("closeSpin");
                            if (res.code === "0000") {
                                this.$Message.success("保存成功!");
                                this.$emit(
                                    "changChildrenData",
                                    "baseInfo",
                                    "formData",
                                    res.data
                                );
                            }
                        })
                        .catch(e => {
                            this.$emit("closeSpin");
                        });
                } else {
                    this.$emit("closeSpin");
                }
            });
        },*/


        submit() {
           let valid = false;
                this.data.forEach((item)=>{
                   if((item.exemptionAmt || item.exemptionAmt == 0) && (item.reductionRatio || item.reductionRatio == 0) ){
                       valid = true;
                   }
                })
            let param ={
                manageCostExemptDetailedList:this.data
            }
            if (valid) {
                saveCostExemptList(this.data).then(res => {
                        this.$emit("closeSpin");
                        if (res.code === "0000") {
                            this.$Message.success("保存成功!");
                            this.$emit(
                                "changChildrenData",
                                "baseInfo",
                                "formData",
                                res.data
                            );
                            this.afs.closeTab(this);
                        }
                    })
                    .catch(e => {
                        this.$emit("closeSpin");
                    });
            } else {
                this.$emit("closeSpin");
            }
        },

        submitToWorkFlow() {
           let valid = false;
                this.data.forEach((item)=>{
                   if((item.exemptionAmt || item.exemptionAmt == 0) && (item.reductionRatio || item.reductionRatio == 0) ){
                       valid = true;
                   }
                })
            let param ={
                manageCostExemptDetailedList:this.data
            }
            if (valid) {
                submitCostExemptList(this.data).then(res => {
                        this.$emit("closeSpin");
                        if (res.code === "0000") {
                            if(res.data=='无单笔限额'){
                                setTimeout(() => {
                                    this.$Modal.warning({
                                        title: "警告",
                                        content: "无单笔合同最大豁免额度，请设置额度",
                                    });
                                },300)
                            }else if(res.data=='无整体限额'){
                                setTimeout(() => {
                                    this.$Modal.warning({
                                        title: "警告",
                                        content: "本部门无豁免额度，请设置额度",
                                    });
                                },300)
                            }else if(res.data.indexOf("单笔限额") > -1){
                                setTimeout(() => {
                                    this.$Modal.warning({
                                        title: "警告",
                                        content: "单笔合同最大豁免金额为：" + res.data.split(",")[1]  + "，您已超额请调整额度",
                                    });
                                },300)

                            }else if(res.data.indexOf("整体限额剩余") > -1){
                                setTimeout(() => {
                                    this.$Modal.warning({
                                        title: "警告",
                                        content: "本部门最大豁免金额剩余：" + res.data.split(",")[1] + "，您已超额请调整额度",
                                    });
                                },300)
                            }else {
                                this.$Message.success("保存成功!");
                                this.$emit(
                                    "changChildrenData",
                                    "baseInfo",
                                    "formData",
                                    res.data
                                );
                                this.afs.closeTab(this);
                            }
                        }
                    })
                    .catch(e => {
                        this.$emit("closeSpin");
                    });
            } else {
                this.$emit("closeSpin");
            }
        },

        approveCostExempt(approvalOperating) {
            let param = {
                approvalOperating:approvalOperating,
                id: this.data[0].exemptId,
                reasonType:""
            }
            //审批结果请求后端方法
            costExemptApprove(param).then(res => {
                this.$emit("closeSpin");
                if (res.code === "0000") {
                    this.$Message.success("操作成功!");
                    this.afs.closeTab(this);
                }
            }).catch(e => {
                    this.$emit("closeSpin");
                });
        },

        /*
         * formData 数据验证 验证通过后 将数据传回父级处理  (保存/提交/审核 通用)
         * @param {String} funcName 回传给父级的方法 (注意父级需要传方法)
         * @param {Object} [data]   父级带来的数据
         */
        formValidate(funcName, data) {
            if (!funcName) return;

            this.$refs.formData.validate(valid => {
                if (valid) {
                    let d = Object.assign({}, data, {}, this.Obj);

                    this.$emit(funcName, d);
                } else {
                    this.$Message.error("验证不通过!");
                    this.$emit("closeSpin");
                    verifyErrorToView(this.$refs.formData.fields);
                }
            });
        },
        getTitle(val) {
            switch (val) {
                case "unsettle" : return "未还清";
                case "settle" : return "已还清";
                case "underReview" : return "审核中";
                case "approved" : return "审核通过";
                case "refuse" : return "拒绝";
                case "toBeRepaired" : return "退回";
                default: return "";
            }


        },

    }
};
</script>
